import React, { useState, useEffect } from 'react';
import { Form, App, Space, Tag, Divider, Modal, Spin } from 'antd';
import { SettingOutlined, EditOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { Card } from '../../components/common/Card';
import { Button } from '../../components/common/Button';
import { Input, TextArea, PasswordInput } from '../../components/common/Input';
import { appConfigService } from '../../services';
import type { AppConfig, SetAppConfigParams } from '../../services';
import './AppConfigPage.css';

interface AppConfigFormValues {
  name: string;
  appId: string;
  appSecret: string;
  type: 'mini_app';
  config: string;
}

export const AppConfigPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [saveLoading, setSaveLoading] = useState(false);
  const [appConfig, setAppConfig] = useState<AppConfig | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [showSecret, setShowSecret] = useState(false);
  const [form] = Form.useForm<AppConfigFormValues>();
  const { message } = App.useApp();

  // 加载小程序配置
  const loadAppConfig = async () => {
    try {
      setLoading(true);
      const response = await appConfigService.getAppConfig();
      if (response.code === 200 && response.data) {
        setAppConfig(response.data);
      }
    } catch (error) {
      message.error('加载小程序配置失败');
      console.error('Load app config failed:', error);
    } finally {
      setLoading(false);
    }
  };

  // 页面初始化
  useEffect(() => {
    loadAppConfig();
  }, []);

  // 打开编辑弹窗
  const handleEdit = () => {
    if (appConfig) {
      form.setFieldsValue({
        name: appConfig.name,
        appId: appConfig.appId,
        appSecret: appConfig.secret,
        type: appConfig.type,
        config: appConfig.config ? appConfig.config.join('\n') : ''
      });
    }
    setEditModalVisible(true);
  };

  // 保存配置
  const handleSave = async (values: AppConfigFormValues) => {
    try {
      setSaveLoading(true);
      
      // 验证配置参数
      const configArray = values.config ? values.config.split('\n').filter(item => item.trim()) : [];
      const params: SetAppConfigParams = {
        name: values.name.trim(),
        appId: values.appId.trim(),
        appSecret: values.appSecret.trim(),
        type: values.type,
        config: configArray.length > 0 ? configArray : undefined
      };

      const validation = appConfigService.validateAppConfig(params);
      if (!validation.isValid) {
        message.error(validation.errors[0]);
        return;
      }

      const response = await appConfigService.setAppConfig(params);
      if (response.code === 200) {
        message.success('小程序配置保存成功');
        setEditModalVisible(false);
        await loadAppConfig(); // 重新加载配置
      } else {
        message.error(response.message || '保存失败');
      }
    } catch (error) {
      message.error('保存小程序配置失败');
      console.error('Save app config failed:', error);
    } finally {
      setSaveLoading(false);
    }
  };

  // 格式化配置显示
  const formatConfig = (config: AppConfig) => {
    return appConfigService.formatAppConfig(config);
  };

  return (
    <div className="app-config-page">
      <div className="page-header">
        <div className="header-content">
          <div className="header-left">
            <SettingOutlined className="header-icon" />
            <div>
              <h1 className="page-title">小程序配置</h1>
              <p className="page-description">管理商户微信小程序的基础配置信息</p>
            </div>
          </div>
          <div className="header-actions">
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={handleEdit}
              disabled={loading}
            >
              编辑配置
            </Button>
          </div>
        </div>
      </div>

      <div className="page-content">
        {loading ? (
          <Card className="config-card">
            <Spin size="large" style={{ display: 'block', textAlign: 'center', padding: '60px 0' }} />
          </Card>
        ) : (
          <Card className="config-card">
            {appConfig ? (
              <div className="config-content">
                <div className="config-header">
                  <div className="config-title">
                    <h3>{appConfig.name}</h3>
                    <Tag color="blue">{formatConfig(appConfig).typeDisplay}</Tag>
                  </div>
                  <div className="config-status">
                    <Tag color="green">已配置</Tag>
                  </div>
                </div>

                <Divider />

                <div className="config-details">
                  <div className="config-row">
                    <div className="config-label">小程序名称</div>
                    <div className="config-value">{appConfig.name}</div>
                  </div>

                  <div className="config-row">
                    <div className="config-label">AppID</div>
                    <div className="config-value">
                      <code>{appConfig.appId}</code>
                    </div>
                  </div>

                  <div className="config-row">
                    <div className="config-label">AppSecret</div>
                    <div className="config-value">
                      <Space>
                        <code>
                          {showSecret ? appConfig.secret : formatConfig(appConfig).secretMasked}
                        </code>
                        <Button
                          type="text"
                          size="small"
                          icon={showSecret ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                          onClick={() => setShowSecret(!showSecret)}
                        >
                          {showSecret ? '隐藏' : '显示'}
                        </Button>
                      </Space>
                    </div>
                  </div>

                  <div className="config-row">
                    <div className="config-label">配置ID</div>
                    <div className="config-value">{appConfig.id}</div>
                  </div>

                  <div className="config-row">
                    <div className="config-label">类型</div>
                    <div className="config-value">
                      <Tag color="blue">{formatConfig(appConfig).typeDisplay}</Tag>
                    </div>
                  </div>

                  <div className="config-row">
                    <div className="config-label">扩展配置</div>
                    <div className="config-value">
                      {appConfig.config && appConfig.config.length > 0 ? (
                        <div className="config-list">
                          {appConfig.config.map((item, index) => (
                            <Tag key={index} className="config-tag">{item}</Tag>
                          ))}
                        </div>
                      ) : (
                        <span className="config-empty">暂无扩展配置</span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="config-empty-state">
                <SettingOutlined className="empty-icon" />
                <h3>暂未配置小程序</h3>
                <p>请点击"编辑配置"按钮设置您的微信小程序配置</p>
                <Button type="primary" icon={<EditOutlined />} onClick={handleEdit}>
                  立即配置
                </Button>
              </div>
            )}
          </Card>
        )}
      </div>

      {/* 编辑配置弹窗 */}
      <Modal
        title="编辑小程序配置"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={600}
        className="edit-config-modal"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          className="config-form"
        >
          <Form.Item
            name="name"
            label="小程序名称"
            rules={[
              { required: true, message: '请输入小程序名称' },
              { max: 50, message: '名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入小程序名称" />
          </Form.Item>

          <Form.Item
            name="appId"
            label="AppID"
            rules={[
              { required: true, message: '请输入AppID' },
              { pattern: /^wx[a-f0-9]{16}$/, message: 'AppID格式不正确，应为wx开头的18位字符' }
            ]}
          >
            <Input placeholder="wx开头的18位字符" />
          </Form.Item>

          <Form.Item
            name="appSecret"
            label="AppSecret"
            rules={[
              { required: true, message: '请输入AppSecret' },
              { pattern: /^[a-f0-9]{32}$/, message: 'AppSecret格式不正确，应为32位十六进制字符' }
            ]}
          >
            <PasswordInput placeholder="32位十六进制字符" />
          </Form.Item>

          <Form.Item
            name="type"
            label="类型"
            initialValue="mini_app"
          >
            <Input disabled value="mini_app" />
          </Form.Item>

          <Form.Item
            name="config"
            label="扩展配置"
            help="每行一个配置项，可选"
          >
            <TextArea 
              placeholder="请输入扩展配置，每行一个配置项"
              rows={4}
            />
          </Form.Item>

          <div className="form-actions">
            <Space>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={saveLoading}
              >
                保存配置
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default AppConfigPage; 